from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
import json
import os
import icon
import Constant as C
import Function as F

from uipy.MainWindow import Uipy_MainWindow
from uipy.frm_start import Uipy_Frm_Start

def init(ui):
    if not os.path.exists('config.json'):
        F.writeInitISConfig()

    with open('config.json','r',encoding='utf-8') as f:
        j = json.loads(f.read())

    oldVer = [int(i) for i in j['版本'].split('.')]
    newVer = [int(i) for i in qApp.applicationVersion().split('.')]

    if newVer == oldVer:
        C.showNewsFrm = False
    else:
        with open('config.json','r',encoding='utf-8') as f:
            j2 = json.loads(f.read())
            j2['版本'] = qApp.applicationVersion()
            j2 = json.dumps(j2,ensure_ascii=False)

        with open('config.json','w',encoding='utf-8') as f:
            f.write(j2)



    C.checkForUpdate = j['启动检查更新']

    if not os.path.exists('Plugin'):
        os.mkdir('Plugin')

    if not os.path.exists('data'):
        os.mkdir('data')

    # 更新
    if C.checkForUpdate:
        if F.checkISpiderUpdate(qApp.applicationVersion()):
            cb = F.msgbox('提示','检测到ISpider有新版本!是否更新',
                          '更新','取消','取消并退出')
            if cb == 'Y':
                QDesktopServices.openUrl(QUrl("https://gitee.com/ruxia-tjy/ispider/releases"))
            elif cb == 'C':
                exit(0)
            del cb

    if not os.path.exists('更新日志.txt'):
        D = F.getNewsTxt()
        if not D['status']:
            F.msgbox('提示',f'下载更新日志时出错！错误{D["error"]}')

    # 获取服务器上的爬虫列表
    rDict = F.getWebPluginList()
    if not rDict['status']:
        F.msgbox('提示',f"{rDict['error']}",'确定并退出')
        exit(0)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setApplicationName('ISpider')
    app.setApplicationVersion('1.0.0.5')
    app.setWindowIcon(QIcon(QPixmap(":/Logo/Res/ISpider.png")))

    uistart = Uipy_Frm_Start()
    init(uistart)
    uistart.close()
    del uistart

    uimain = Uipy_MainWindow()

    sys.exit(app.exec_())
